"use client"

import { useState, useRef, useCallback } from "react"
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Slider } from "@/components/ui/slider"
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
import { useToast } from "@/components/ui/use-toast"
import {
  BarChart3,
  LineChartIcon,
  PieChartIcon,
  Activity,
  Gauge,
  ScatterChartIcon,
  Radar,
  Save,
  Download,
  Upload,
  Smartphone,
  Tablet,
  Monitor,
  ImageIcon,
  Loader2,
  Grid3x3,
  CircleDot,
  CandlestickChartIcon as CandlestickIcon,
  LayoutGrid,
  FilterX,
  ChevronLeft,
  ChevronRight,
  Settings,
  Copy,
  Trash2,
  Maximize,
  Database,
  Palette,
  Sliders,
} from "lucide-react"
import {
  BarChart,
  LineChart,
  PieChart,
  AreaChart,
  GaugeChart,
  ScatterChart,
  RadarChart,
  HeatmapChart,
  BubbleChart,
  CandlestickChart,
  TreemapChart,
  FunnelChart,
} from "@/components/dashboard/chart-components"

// 在文件顶部添加 html2canvas 导入
import html2canvas from "html2canvas"

// 图表组件映射
const chartComponents = {
  bar: BarChart,
  line: LineChart,
  pie: PieChart,
  area: AreaChart,
  gauge: GaugeChart,
  scatter: ScatterChart,
  radar: RadarChart,
  heatmap: HeatmapChart,
  bubble: BubbleChart,
  candlestick: CandlestickChart,
  treemap: TreemapChart,
  funnel: FunnelChart,
}

// 图表图标映射
const chartIcons = {
  bar: <BarChart3 className="h-4 w-4" />,
  line: <LineChartIcon className="h-4 w-4" />,
  pie: <PieChartIcon className="h-4 w-4" />,
  area: <Activity className="h-4 w-4" />,
  gauge: <Gauge className="h-4 w-4" />,
  scatter: <ScatterChartIcon className="h-4 w-4" />,
  radar: <Radar className="h-4 w-4" />,
  heatmap: <Grid3x3 className="h-4 w-4" />,
  bubble: <CircleDot className="h-4 w-4" />,
  candlestick: <CandlestickIcon className="h-4 w-4" />,
  treemap: <LayoutGrid className="h-4 w-4" />,
  funnel: <FilterX className="h-4 w-4" />,
}

// 初始图表数据
const initialCharts = [
  {
    id: "chart-1",
    type: "bar",
    title: "销售数据",
    width: 6,
    height: 2,
    data: {
      labels: ["一月", "二月", "三月", "四月", "五月", "六月"],
      datasets: [
        {
          label: "销售额",
          data: [65, 59, 80, 81, 56, 55],
          backgroundColor: "#3498db",
        },
      ],
    },
    options: {
      animation: true,
      theme: "light",
      showLegend: true,
      borderWidth: 1,
      tension: 0.4,
    },
  },
  {
    id: "chart-2",
    type: "line",
    title: "用户增长",
    width: 6,
    height: 2,
    data: {
      labels: ["一月", "二月", "三月", "四月", "五月", "六月"],
      datasets: [
        {
          label: "新用户",
          data: [28, 48, 40, 19, 86, 27],
          borderColor: "#2ecc71",
          backgroundColor: "rgba(46, 204, 113, 0.2)",
        },
      ],
    },
    options: {
      animation: true,
      theme: "light",
      showLegend: true,
      borderWidth: 2,
      tension: 0.4,
    },
  },
]

// 屏幕尺寸配置
const screenSizes = {
  mobile: {
    width: 375,
    height: 667,
    label: "手机",
    icon: <Smartphone className="h-4 w-4" />,
  },
  tablet: {
    width: 768,
    height: 1024,
    label: "平板",
    icon: <Tablet className="h-4 w-4" />,
  },
  desktop: {
    width: "100%",
    height: "auto",
    label: "桌面",
    icon: <Monitor className="h-4 w-4" />,
  },
}

export default function DashboardPage() {
  const [charts, setCharts] = useState(initialCharts)
  const [selectedChart, setSelectedChart] = useState(null)
  const [dashboardTitle, setDashboardTitle] = useState("我的可视化大屏")
  const [theme, setTheme] = useState("light")
  const [screenSize, setScreenSize] = useState("desktop")
  const [isExporting, setIsExporting] = useState(false)
  const [isFullscreen, setIsFullscreen] = useState(false)
  const [leftPanelOpen, setLeftPanelOpen] = useState(true)
  const [rightPanelOpen, setRightPanelOpen] = useState(true)
  const [activeTab, setActiveTab] = useState("design")
  const previewRef = useRef(null)
  const { toast } = useToast()

  // 处理拖拽结束
  const onDragEnd = useCallback(
    (result) => {
      if (!result.destination) return

      const items = Array.from(charts)
      const [reorderedItem] = items.splice(result.source.index, 1)
      items.splice(result.destination.index, 0, reorderedItem)

      setCharts(items)
    },
    [charts],
  )

  // 添加图表
  const addChart = useCallback(
    (type) => {
      const newChart = {
        id: `chart-${Date.now()}`,
        type,
        title: `新${type}图表`,
        width: 6,
        height: 2,
        data: {
          labels: ["一月", "二月", "三月", "四月", "五月", "六月"],
          datasets: [
            {
              label: "数据系列",
              data: [
                Math.floor(Math.random() * 100),
                Math.floor(Math.random() * 100),
                Math.floor(Math.random() * 100),
                Math.floor(Math.random() * 100),
                Math.floor(Math.random() * 100),
                Math.floor(Math.random() * 100),
              ],
              backgroundColor: "#3498db",
              borderColor: "#3498db",
            },
          ],
        },
        options: {
          animation: true,
          theme,
          showLegend: true,
          borderWidth: 1,
          tension: 0.4,
        },
      }

      setCharts([...charts, newChart])

      toast({
        title: "图表已添加",
        description: `已成功添加新的${type}图表`,
      })
    },
    [charts, theme, toast],
  )

  // 复制图表
  const duplicateChart = useCallback(
    (chartId) => {
      const chartToDuplicate = charts.find((chart) => chart.id === chartId)
      if (!chartToDuplicate) return

      const newChart = {
        ...chartToDuplicate,
        id: `chart-${Date.now()}`,
        title: `${chartToDuplicate.title} (副本)`,
      }

      setCharts([...charts, newChart])

      toast({
        title: "图表已复制",
        description: "已成功创建图表副本",
      })
    },
    [charts, toast],
  )

  // 删除图表
  const deleteChart = useCallback(
    (chartId) => {
      setCharts(charts.filter((chart) => chart.id !== chartId))
      if (selectedChart && selectedChart.id === chartId) {
        setSelectedChart(null)
      }

      toast({
        title: "图表已删除",
        description: "已成功删除选中的图表",
      })
    },
    [charts, selectedChart, toast],
  )

  // 更新图表配置
  const updateChartConfig = useCallback(
    (chartId, config) => {
      setCharts(charts.map((chart) => (chart.id === chartId ? { ...chart, ...config } : chart)))

      if (selectedChart && selectedChart.id === chartId) {
        setSelectedChart({ ...selectedChart, ...config })
      }
    },
    [charts, selectedChart],
  )

  // 更新图表数据
  const updateChartData = useCallback(
    (chartId, data) => {
      setCharts(
        charts.map((chart) => {
          if (chart.id === chartId) {
            return {
              ...chart,
              data: {
                ...chart.data,
                ...data,
              },
            }
          }
          return chart
        }),
      )

      if (selectedChart && selectedChart.id === chartId) {
        setSelectedChart({
          ...selectedChart,
          data: {
            ...selectedChart.data,
            ...data,
          },
        })
      }
    },
    [charts, selectedChart],
  )

  // 更新图表选项
  const updateChartOptions = useCallback(
    (chartId, options) => {
      setCharts(
        charts.map((chart) => {
          if (chart.id === chartId) {
            return {
              ...chart,
              options: {
                ...chart.options,
                ...options,
              },
            }
          }
          return chart
        }),
      )

      if (selectedChart && selectedChart.id === chartId) {
        setSelectedChart({
          ...selectedChart,
          options: {
            ...selectedChart.options,
            ...options,
          },
        })
      }
    },
    [charts, selectedChart],
  )

  // 更新图表宽度
  const updateChartWidth = useCallback(
    (chartId, width) => {
      setCharts(
        charts.map((chart) => {
          if (chart.id === chartId) {
            return {
              ...chart,
              width,
            }
          }
          return chart
        }),
      )

      if (selectedChart && selectedChart.id === chartId) {
        setSelectedChart({
          ...selectedChart,
          width,
        })
      }
    },
    [charts, selectedChart],
  )

  // 更新图表高度
  const updateChartHeight = useCallback(
    (chartId, height) => {
      setCharts(
        charts.map((chart) => {
          if (chart.id === chartId) {
            return {
              ...chart,
              height,
            }
          }
          return chart
        }),
      )

      if (selectedChart && selectedChart.id === chartId) {
        setSelectedChart({
          ...selectedChart,
          height,
        })
      }
    },
    [charts, selectedChart],
  )

  // 保存仪表板
  const saveDashboard = useCallback(() => {
    const dashboard = {
      title: dashboardTitle,
      charts,
      theme,
    }
    localStorage.setItem("dashboard", JSON.stringify(dashboard))

    toast({
      title: "保存成功",
      description: "您的大屏设计已保存到本地",
    })
  }, [dashboardTitle, charts, theme, toast])

  // 加载仪表板
  const loadDashboard = useCallback(() => {
    const savedDashboard = localStorage.getItem("dashboard")
    if (savedDashboard) {
      const dashboard = JSON.parse(savedDashboard)
      setDashboardTitle(dashboard.title || "我的可视化大屏")
      setCharts(dashboard.charts || [])
      setTheme(dashboard.theme || "light")

      toast({
        title: "加载成功",
        description: "已从本地加载大屏设计",
      })
    } else {
      toast({
        title: "加载失败",
        description: "未找到已保存的大屏设计",
        variant: "destructive",
      })
    }
  }, [toast])

  // 导出为JSON
  const exportDashboard = useCallback(() => {
    const dashboard = {
      title: dashboardTitle,
      charts,
      theme,
    }
    const dataStr = JSON.stringify(dashboard, null, 2)
    const dataUri = "data:application/json;charset=utf-8," + encodeURIComponent(dataStr)

    const exportFileDefaultName = "dashboard.json"

    const linkElement = document.createElement("a")
    linkElement.setAttribute("href", dataUri)
    linkElement.setAttribute("download", exportFileDefaultName)
    linkElement.click()

    toast({
      title: "导出成功",
      description: "已将大屏设计导出为JSON文件",
    })
  }, [dashboardTitle, charts, theme, toast])

  // 导出为图片
  const exportAsImage = useCallback(async () => {
    if (!previewRef.current) {
      toast({
        title: "导出失败",
        description: "无法获取预览区域",
        variant: "destructive",
      })
      return
    }

    setIsExporting(true)

    try {
      const canvas = await html2canvas(previewRef.current, {
        backgroundColor: theme === "dark" ? "#111827" : "#ffffff",
        scale: 2, // 提高导出图片的清晰度
        logging: false,
        allowTaint: true,
        useCORS: true,
      })

      // 创建下载链接
      const link = document.createElement("a")
      link.download = `${dashboardTitle.replace(/\s+/g, "-")}-${new Date().toISOString().slice(0, 10)}.png`
      link.href = canvas.toDataURL("image/png")
      link.click()

      toast({
        title: "导出成功",
        description: "已将大屏设计导出为高清图片",
      })
    } catch (error) {
      console.error("导出图片失败:", error)
      toast({
        title: "导出失败",
        description: "导出图片时发生错误: " + (error.message || "未知错误"),
        variant: "destructive",
      })
    } finally {
      setIsExporting(false)
    }
  }, [previewRef, theme, dashboardTitle, toast])

  // 应用主题到所有图表
  const applyThemeToAllCharts = useCallback(
    (newTheme) => {
      setTheme(newTheme)
      setCharts(
        charts.map((chart) => ({
          ...chart,
          options: {
            ...chart.options,
            theme: newTheme,
          },
        })),
      )
    },
    [charts],
  )

  // 切换全屏模式
  const toggleFullscreen = useCallback(() => {
    if (!document.fullscreenElement) {
      if (previewRef.current.requestFullscreen) {
        previewRef.current.requestFullscreen()
        setIsFullscreen(true)
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen()
        setIsFullscreen(false)
      }
    }
  }, [previewRef])

  // 图表配置组件
  const ChartConfig = ({ chart }) => {
    const [activeConfigTab, setActiveConfigTab] = useState("general")
    const [labels, setLabels] = useState(chart.data.labels.join(", "))
    const [dataValues, setDataValues] = useState(chart.data.datasets[0].data.join(", "))
    const [datasetLabel, setDatasetLabel] = useState(chart.data.datasets[0].label)

    const handleSaveData = () => {
      const labelsArray = labels.split(",").map((label) => label.trim())
      const dataArray = dataValues.split(",").map((value) => Number(value.trim()))

      updateChartData(chart.id, {
        labels: labelsArray,
        datasets: [
          {
            ...chart.data.datasets[0],
            label: datasetLabel,
            data: dataArray,
          },
        ],
      })

      toast({
        title: "数据已更新",
        description: "图表数据已成功更新",
      })
    }

    return (
      <div className="space-y-4">
        <Tabs value={activeConfigTab} onValueChange={setActiveConfigTab}>
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="general" className="text-xs">
              <Settings className="h-3 w-3 mr-1" />
              常规
            </TabsTrigger>
            <TabsTrigger value="data" className="text-xs">
              <Database className="h-3 w-3 mr-1" />
              数据
            </TabsTrigger>
            <TabsTrigger value="style" className="text-xs">
              <Palette className="h-3 w-3 mr-1" />
              样式
            </TabsTrigger>
            <TabsTrigger value="layout" className="text-xs">
              <Sliders className="h-3 w-3 mr-1" />
              布局
            </TabsTrigger>
          </TabsList>

          <TabsContent value="general" className="space-y-4 pt-4">
            <div className="grid gap-2">
              <Label htmlFor="title">图表标题</Label>
              <Input
                id="title"
                value={chart.title}
                onChange={(e) => updateChartConfig(chart.id, { title: e.target.value })}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="chartType">图表类型</Label>
              <Select value={chart.type} onValueChange={(value) => updateChartConfig(chart.id, { type: value })}>
                <SelectTrigger id="chartType">
                  <SelectValue placeholder="选择图表类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="bar">柱状图</SelectItem>
                  <SelectItem value="line">折线图</SelectItem>
                  <SelectItem value="pie">饼图</SelectItem>
                  <SelectItem value="area">面积图</SelectItem>
                  <SelectItem value="gauge">仪表盘</SelectItem>
                  <SelectItem value="scatter">散点图</SelectItem>
                  <SelectItem value="radar">雷达图</SelectItem>
                  <SelectItem value="heatmap">热力图</SelectItem>
                  <SelectItem value="bubble">气泡图</SelectItem>
                  <SelectItem value="candlestick">K线图</SelectItem>
                  <SelectItem value="treemap">矩形树图</SelectItem>
                  <SelectItem value="funnel">漏斗图</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center space-x-2">
              <Switch
                id="animation"
                checked={chart.options.animation}
                onCheckedChange={(checked) => updateChartOptions(chart.id, { animation: checked })}
              />
              <Label htmlFor="animation">启用动画</Label>
            </div>

            <div className="flex items-center space-x-2">
              <Switch
                id="showLegend"
                checked={chart.options.showLegend}
                onCheckedChange={(checked) => updateChartOptions(chart.id, { showLegend: checked })}
              />
              <Label htmlFor="showLegend">显示图例</Label>
            </div>
          </TabsContent>

          <TabsContent value="data" className="space-y-4 pt-4">
            <div className="grid gap-2">
              <Label htmlFor="datasetLabel">数据系列名称</Label>
              <Input id="datasetLabel" value={datasetLabel} onChange={(e) => setDatasetLabel(e.target.value)} />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="labels">标签 (逗号分隔)</Label>
              <Input id="labels" value={labels} onChange={(e) => setLabels(e.target.value)} />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="dataValues">数据值 (逗号分隔)</Label>
              <Input id="dataValues" value={dataValues} onChange={(e) => setDataValues(e.target.value)} />
            </div>

            <Popover>
              <PopoverTrigger asChild>
                <Button variant="outline" size="sm" className="w-full">
                  导入JSON数据
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-80">
                <div className="grid gap-4">
                  <div className="space-y-2">
                    <h4 className="font-medium leading-none">JSON数据</h4>
                    <p className="text-sm text-muted-foreground">
                      粘贴符合Chart.js格式的JSON数据，包含labels和datasets字段
                    </p>
                  </div>
                  <Textarea
                    placeholder='{"labels":["一月","二月"],"datasets":[{"label":"销售额","data":[65,59]}]}'
                    className="h-24"
                    id="jsonData"
                  />
                  <Button
                    onClick={() => {
                      try {
                        const jsonData = document.getElementById("jsonData").value
                        const data = JSON.parse(jsonData)
                        if (data.labels) setLabels(data.labels.join(", "))
                        if (data.datasets && data.datasets[0]) {
                          setDataValues(data.datasets[0].data.join(", "))
                          if (data.datasets[0].label) setDatasetLabel(data.datasets[0].label)
                        }
                        toast({
                          title: "数据已导入",
                          description: "JSON数据已成功导入",
                        })
                      } catch (error) {
                        toast({
                          title: "导入失败",
                          description: "JSON格式不正确",
                          variant: "destructive",
                        })
                      }
                    }}
                  >
                    导入
                  </Button>
                </div>
              </PopoverContent>
            </Popover>

            <Button onClick={handleSaveData} className="w-full">
              保存数据
            </Button>
          </TabsContent>

          <TabsContent value="style" className="space-y-4 pt-4">
            <div className="grid gap-2">
              <Label htmlFor="backgroundColor">背景颜色</Label>
              <div className="flex gap-2">
                <Input
                  type="color"
                  id="backgroundColor"
                  value={chart.data.datasets[0].backgroundColor || "#3498db"}
                  onChange={(e) => {
                    const newDatasets = [...chart.data.datasets]
                    newDatasets[0] = { ...newDatasets[0], backgroundColor: e.target.value }
                    updateChartData(chart.id, { datasets: newDatasets })
                  }}
                  className="w-12 h-8 p-1"
                />
                <Input
                  type="text"
                  value={chart.data.datasets[0].backgroundColor || "#3498db"}
                  onChange={(e) => {
                    const newDatasets = [...chart.data.datasets]
                    newDatasets[0] = { ...newDatasets[0], backgroundColor: e.target.value }
                    updateChartData(chart.id, { datasets: newDatasets })
                  }}
                  className="flex-1"
                />
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="borderColor">边框颜色</Label>
              <div className="flex gap-2">
                <Input
                  type="color"
                  id="borderColor"
                  value={chart.data.datasets[0].borderColor || "#3498db"}
                  onChange={(e) => {
                    const newDatasets = [...chart.data.datasets]
                    newDatasets[0] = { ...newDatasets[0], borderColor: e.target.value }
                    updateChartData(chart.id, { datasets: newDatasets })
                  }}
                  className="w-12 h-8 p-1"
                />
                <Input
                  type="text"
                  value={chart.data.datasets[0].borderColor || "#3498db"}
                  onChange={(e) => {
                    const newDatasets = [...chart.data.datasets]
                    newDatasets[0] = { ...newDatasets[0], borderColor: e.target.value }
                    updateChartData(chart.id, { datasets: newDatasets })
                  }}
                  className="flex-1"
                />
              </div>
            </div>

            <div className="grid gap-2">
              <div className="flex justify-between">
                <Label htmlFor="borderWidth">边框宽度</Label>
                <span className="text-sm text-muted-foreground">{chart.options.borderWidth}px</span>
              </div>
              <Slider
                id="borderWidth"
                min={0}
                max={10}
                step={1}
                value={[chart.options.borderWidth]}
                onValueChange={(value) => updateChartOptions(chart.id, { borderWidth: value[0] })}
              />
            </div>

            {(chart.type === "line" || chart.type === "area") && (
              <div className="grid gap-2">
                <div className="flex justify-between">
                  <Label htmlFor="tension">曲线平滑度</Label>
                  <span className="text-sm text-muted-foreground">{chart.options.tension}</span>
                </div>
                <Slider
                  id="tension"
                  min={0}
                  max={1}
                  step={0.1}
                  value={[chart.options.tension]}
                  onValueChange={(value) => updateChartOptions(chart.id, { tension: value[0] })}
                />
              </div>
            )}
          </TabsContent>

          <TabsContent value="layout" className="space-y-4 pt-4">
            <div className="grid gap-2">
              <div className="flex justify-between">
                <Label htmlFor="chartWidth">图表宽度</Label>
                <span className="text-sm text-muted-foreground">{chart.width}/12</span>
              </div>
              <Slider
                id="chartWidth"
                min={1}
                max={12}
                step={1}
                value={[chart.width]}
                onValueChange={(value) => updateChartWidth(chart.id, value[0])}
              />
            </div>

            <div className="grid gap-2">
              <div className="flex justify-between">
                <Label htmlFor="chartHeight">图表高度</Label>
                <span className="text-sm text-muted-foreground">{chart.height}</span>
              </div>
              <Slider
                id="chartHeight"
                min={1}
                max={6}
                step={0.5}
                value={[chart.height]}
                onValueChange={(value) => updateChartHeight(chart.id, value[0])}
              />
            </div>
          </TabsContent>
        </Tabs>

        <div className="flex gap-2">
          <Button onClick={() => duplicateChart(chart.id)} variant="outline" className="flex-1">
            <Copy className="h-4 w-4 mr-2" />
            复制
          </Button>
          <Button onClick={() => deleteChart(chart.id)} variant="destructive" className="flex-1">
            <Trash2 className="h-4 w-4 mr-2" />
            删除
          </Button>
        </div>
      </div>
    )
  }

  return (
    <div className="h-[calc(100vh-4rem)] overflow-hidden flex flex-col">
      {/* 顶部工具栏 */}
      <div className="border-b p-2 flex justify-between items-center">
        <div className="flex items-center gap-4">
          <Input
            value={dashboardTitle}
            onChange={(e) => setDashboardTitle(e.target.value)}
            className="text-xl font-bold w-[300px]"
          />
          <Tabs value={activeTab} onValueChange={setActiveTab} className="ml-4">
            <TabsList>
              <TabsTrigger value="design">设计</TabsTrigger>
              <TabsTrigger value="preview">预览</TabsTrigger>
            </TabsList>
          </Tabs>
        </div>
        <div className="flex items-center gap-2">
          <Select value={theme} onValueChange={applyThemeToAllCharts}>
            <SelectTrigger className="w-[120px]">
              <SelectValue placeholder="选择主题" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="light">浅色主题</SelectItem>
              <SelectItem value="dark">深色主题</SelectItem>
            </SelectContent>
          </Select>

          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button onClick={saveDashboard} size="sm" variant="outline">
                  <Save className="h-4 w-4 mr-2" />
                  保存
                </Button>
              </TooltipTrigger>
              <TooltipContent>保存到本地</TooltipContent>
            </Tooltip>
          </TooltipProvider>

          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button onClick={loadDashboard} size="sm" variant="outline">
                  <Upload className="h-4 w-4 mr-2" />
                  加载
                </Button>
              </TooltipTrigger>
              <TooltipContent>从本地加载</TooltipContent>
            </Tooltip>
          </TooltipProvider>

          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button onClick={exportDashboard} size="sm" variant="outline">
                  <Download className="h-4 w-4 mr-2" />
                  导出JSON
                </Button>
              </TooltipTrigger>
              <TooltipContent>导出为JSON文件</TooltipContent>
            </Tooltip>
          </TooltipProvider>

          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button onClick={exportAsImage} size="sm" variant="outline" disabled={isExporting}>
                  {isExporting ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      导出中...
                    </>
                  ) : (
                    <>
                      <ImageIcon className="h-4 w-4 mr-2" />
                      导出图片
                    </>
                  )}
                </Button>
              </TooltipTrigger>
              <TooltipContent>导出为高清图片</TooltipContent>
            </Tooltip>
          </TooltipProvider>
        </div>
      </div>

      <div className="flex-1 flex overflow-hidden">
        {/* 左侧面板 - 图表库 */}
        <div
          className={`border-r bg-background transition-all duration-300 ${
            leftPanelOpen ? "w-64" : "w-12"
          } flex flex-col`}
        >
          <div className="p-2 border-b flex justify-between items-center">
            {leftPanelOpen && <h3 className="font-medium">图表库</h3>}
            <Button variant="ghost" size="icon" onClick={() => setLeftPanelOpen(!leftPanelOpen)} className="h-8 w-8">
              {leftPanelOpen ? <ChevronLeft className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
            </Button>
          </div>

          {leftPanelOpen && (
            <div className="p-2 overflow-y-auto flex-1">
              <div className="grid grid-cols-2 gap-2">
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("bar")}
                >
                  <BarChart3 className="h-8 w-8" />
                  <span className="text-xs">柱状图</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("line")}
                >
                  <LineChartIcon className="h-8 w-8" />
                  <span className="text-xs">折线图</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("pie")}
                >
                  <PieChartIcon className="h-8 w-8" />
                  <span className="text-xs">饼图</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("area")}
                >
                  <Activity className="h-8 w-8" />
                  <span className="text-xs">面积图</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("gauge")}
                >
                  <Gauge className="h-8 w-8" />
                  <span className="text-xs">仪表盘</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("scatter")}
                >
                  <ScatterChartIcon className="h-8 w-8" />
                  <span className="text-xs">散点图</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("radar")}
                >
                  <Radar className="h-8 w-8" />
                  <span className="text-xs">雷达图</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("heatmap")}
                >
                  <Grid3x3 className="h-8 w-8" />
                  <span className="text-xs">热力图</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("bubble")}
                >
                  <CircleDot className="h-8 w-8" />
                  <span className="text-xs">气泡图</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("candlestick")}
                >
                  <CandlestickIcon className="h-8 w-8" />
                  <span className="text-xs">K线图</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("treemap")}
                >
                  <LayoutGrid className="h-8 w-8" />
                  <span className="text-xs">矩形树图</span>
                </Button>
                <Button
                  variant="outline"
                  className="flex flex-col items-center justify-center h-20 gap-1"
                  onClick={() => addChart("funnel")}
                >
                  <FilterX className="h-8 w-8" />
                  <span className="text-xs">漏斗图</span>
                </Button>
              </div>
            </div>
          )}
        </div>

        {/* 中间内容区 */}
        <div className="flex-1 overflow-auto p-4 bg-muted/30">
          {activeTab === "design" ? (
            <div
              className={`grid grid-cols-12 gap-4 p-4 rounded-lg min-h-full ${
                theme === "dark" ? "bg-gray-900 text-white" : "bg-white border"
              }`}
            >
              <DragDropContext onDragEnd={onDragEnd}>
                <Droppable droppableId="charts" direction="vertical">
                  {(provided) => (
                    <div
                      className="col-span-12 grid grid-cols-12 gap-4"
                      {...provided.droppableProps}
                      ref={provided.innerRef}
                    >
                      {charts.length > 0 ? (
                        charts.map((chart, index) => {
                          const ChartComponent = chartComponents[chart.type]
                          return (
                            <Draggable key={chart.id} draggableId={chart.id} index={index}>
                              {(provided) => (
                                <div
                                  className={`col-span-${chart.width} ${
                                    selectedChart && selectedChart.id === chart.id ? "ring-2 ring-primary" : ""
                                  }`}
                                  ref={provided.innerRef}
                                  {...provided.draggableProps}
                                >
                                  <div
                                    className={`border rounded-lg p-4 ${
                                      theme === "dark" ? "border-gray-700" : ""
                                    } h-full relative`}
                                  >
                                    <div className="flex justify-between items-center mb-2">
                                      <div className="font-medium flex items-center" {...provided.dragHandleProps}>
                                        {chartIcons[chart.type]}
                                        <span className="ml-2">{chart.title}</span>
                                      </div>
                                      <div className="flex gap-1">
                                        <TooltipProvider>
                                          <Tooltip>
                                            <TooltipTrigger asChild>
                                              <Button
                                                variant="ghost"
                                                size="icon"
                                                className="h-6 w-6"
                                                onClick={() => setSelectedChart(chart)}
                                              >
                                                <Settings className="h-4 w-4" />
                                              </Button>
                                            </TooltipTrigger>
                                            <TooltipContent>编辑图表</TooltipContent>
                                          </Tooltip>
                                        </TooltipProvider>

                                        <TooltipProvider>
                                          <Tooltip>
                                            <TooltipTrigger asChild>
                                              <Button
                                                variant="ghost"
                                                size="icon"
                                                className="h-6 w-6"
                                                onClick={() => duplicateChart(chart.id)}
                                              >
                                                <Copy className="h-4 w-4" />
                                              </Button>
                                            </TooltipTrigger>
                                            <TooltipContent>复制图表</TooltipContent>
                                          </Tooltip>
                                        </TooltipProvider>

                                        <TooltipProvider>
                                          <Tooltip>
                                            <TooltipTrigger asChild>
                                              <Button
                                                variant="ghost"
                                                size="icon"
                                                className="h-6 w-6 text-red-500 hover:text-red-700 hover:bg-red-50"
                                                onClick={() => deleteChart(chart.id)}
                                              >
                                                <Trash2 className="h-4 w-4" />
                                              </Button>
                                            </TooltipTrigger>
                                            <TooltipContent>删除图表</TooltipContent>
                                          </Tooltip>
                                        </TooltipProvider>
                                      </div>
                                    </div>
                                    <div className="h-[calc(100%-2rem)]" style={{ height: `${chart.height * 100}px` }}>
                                      <ChartComponent data={chart.data} options={chart.options} />
                                    </div>
                                  </div>
                                </div>
                              )}
                            </Draggable>
                          )
                        })
                      ) : (
                        <div className="col-span-12 flex flex-col items-center justify-center py-12 text-muted-foreground">
                          <BarChart3 className="h-12 w-12 mb-4" />
                          <p className="text-lg font-medium">暂无图表</p>
                          <p className="text-sm">从左侧添加图表开始创建您的可视化大屏</p>
                        </div>
                      )}
                      {provided.placeholder}
                    </div>
                  )}
                </Droppable>
              </DragDropContext>
            </div>
          ) : (
            <div className="h-full">
              <div className="mb-4 flex justify-between items-center">
                <h2 className="text-lg font-medium">预览模式</h2>
                <div className="flex items-center gap-2">
                  <Select value={screenSize} onValueChange={setScreenSize}>
                    <SelectTrigger className="w-[180px]">
                      <SelectValue placeholder="选择屏幕尺寸" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="mobile">
                        <div className="flex items-center gap-2">
                          <Smartphone className="h-4 w-4" />
                          <span>手机 (375x667)</span>
                        </div>
                      </SelectItem>
                      <SelectItem value="tablet">
                        <div className="flex items-center gap-2">
                          <Tablet className="h-4 w-4" />
                          <span>平板 (768x1024)</span>
                        </div>
                      </SelectItem>
                      <SelectItem value="desktop">
                        <div className="flex items-center gap-2">
                          <Monitor className="h-4 w-4" />
                          <span>桌面 (全屏)</span>
                        </div>
                      </SelectItem>
                    </SelectContent>
                  </Select>

                  <Button onClick={toggleFullscreen} size="sm" variant="outline">
                    <Maximize className="h-4 w-4 mr-2" />
                    全屏预览
                  </Button>
                </div>
              </div>

              <div className="flex justify-center">
                <div
                  ref={previewRef}
                  style={{
                    width: screenSizes[screenSize].width,
                    height: screenSizes[screenSize].height,
                    overflow: "auto",
                  }}
                  className={`p-6 rounded-lg border ${theme === "dark" ? "bg-gray-900 text-white" : "bg-white"}`}
                >
                  <h1 className="text-2xl font-bold mb-6">{dashboardTitle}</h1>

                  <div className="grid grid-cols-12 gap-4">
                    {charts.map((chart) => {
                      const ChartComponent = chartComponents[chart.type]
                      const colWidth = screenSize === "mobile" ? 12 : chart.width

                      return (
                        <div key={chart.id} className={`col-span-${colWidth}`}>
                          <div className={`border rounded-lg p-4 ${theme === "dark" ? "border-gray-700" : ""}`}>
                            <div className="font-medium mb-2 flex items-center">
                              {chartIcons[chart.type]}
                              <span className="ml-2">{chart.title}</span>
                            </div>
                            <div style={{ height: `${chart.height * 100}px` }}>
                              <ChartComponent data={chart.data} options={chart.options} />
                            </div>
                          </div>
                        </div>
                      )
                    })}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 右侧面板 - 图表配置 */}
        <div
          className={`border-l bg-background transition-all duration-300 ${
            rightPanelOpen ? "w-80" : "w-12"
          } flex flex-col`}
        >
          <div className="p-2 border-b flex justify-between items-center">
            <Button variant="ghost" size="icon" onClick={() => setRightPanelOpen(!rightPanelOpen)} className="h-8 w-8">
              {rightPanelOpen ? <ChevronRight className="h-4 w-4" /> : <ChevronLeft className="h-4 w-4" />}
            </Button>
            {rightPanelOpen && <h3 className="font-medium">图表配置</h3>}
          </div>

          {rightPanelOpen && (
            <div className="p-2 overflow-y-auto flex-1">
              {selectedChart ? (
                <ChartConfig chart={selectedChart} />
              ) : (
                <div className="flex flex-col items-center justify-center h-full text-muted-foreground">
                  <Settings className="h-12 w-12 mb-4" />
                  <p className="text-center">选择一个图表进行配置</p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
